<template>
	<view>
<!-- 		<view class="top">
			<text class="topText">报修软件购买电话：18850331555</text>
		</view>
		<view class="two">
			<u-notice-bar :text="text1" mode="closable"></u-notice-bar>
		</view> -->
		<view class="formBox">
			<u--form :model="form" ref="uForm" :rules="rules">
				<!-- <br/> -->
				<view class="labelBox">
					<u-form-item label="联系人" labelWidth="200rpx" prop="name" >
					</u-form-item>
				</view>
				<u-input placeholder="请输入联系人" v-model="form.name" />
				
				<view class="labelBox">
					<u-form-item label="联系电话" labelWidth="140rpx" prop="phoneNumber" >
					</u-form-item>
				</view>
				<u-input placeholder="请输入联系电话" v-model="form.phoneNumber" />
<!-- 				<view class="labelBox">
					<u-form-item label="填报部门" labelWidth="140rpx" prop="phoneNumber" >
					</u-form-item>
				</view>
				<view style="width: 80%;margin: 0 auto;margin-top: -70rpx;margin-left: 160rpx;background-color: white;">
					<uni-combox v-model="form.tbbm1" :candidates="ccelist" @input="inputccelist"
						placeholder="请选择" emptyTips="无数据"
						></uni-combox>
				</view> -->
				<view class="labelBox">
					<u-form-item label="具体位置" labelWidth="140rpx" prop="adderss" >
					</u-form-item>
				</view>
				<view class="labelBox" style="background-color: white;">
					<uni-combox v-model="form.cj" :candidates="cjlist" 
						placeholder="车间" emptyTips="无数据" style="width: 150rpx;"></uni-combox>
					<uni-combox v-model="form.kh" :candidates="khlist" 
						placeholder="跨号" emptyTips="无数据" style="width: 150rpx;"></uni-combox>
					<u-input placeholder="柱头号" v-model="form.zth"  style="width: 150rpx;"/>	
				</view>
				<u-input placeholder="请输入具体地点" v-model="form.adderss" />
				<view class="labelBox">
					<u-form-item label="隐患描述" labelWidth="140rpx" prop="gzms" >
					</u-form-item>
				</view>
				<u-input placeholder="请您描述隐患问题具体情况" v-model="form.gzms" />
				
				<view class="labelBox">
					<u-form-item label="隐患照片" labelWidth="150rpx" prop="photo" >
					</u-form-item>
				</view>
				<!-- <u-input v-model="form.photo"> -->
				<view class="photoBox">
					<u-upload
							:fileList="fileList1"
							@afterRead="afterRead"
							@delete="deletePic"
							name="1"
							multiple
							:maxCount="3"
						></u-upload>
				</view>
			</u--form>
			<view class="btn">
				<u-button class="btn" type="primary" 
					@click="submit(form)" :disabled="isClick">上报</u-button>	
			</view>
		</view>
	</view>
</template>

<script>
	import * as dd from 'dingtalk-jsapi'
	export default {
		data() {
			return {
				userInfo: {},
				text1: '',
				ccelist:[],
				form: {
						tbbm1:'',
						YTBBM:'',
						name: '',
						phoneNumber: '',
						adderss: '',
						gzsb: '',
						gzms: '',
						ly: '',
						photo: '',
						cj:'',
						kh:'',
						zth:'',
					},
				rules: {
					name: [
						{
							required: true,
							message: '请输入联系人',
							trigger: ['blur', 'change']
						}
					],
					phoneNumber: [
						{
							required: true,
							message: '请输入联系电话',
							trigger: ['blur', 'change']
						}
					],
							adderss: [
						{
							required: true,
							message: '请输入具体地点',
							trigger: ['blur', 'change']
									}
							],
							gzsb: [
						{
							required: true,
							message: '请选择故障设备',
							trigger: ['blur', 'change']
									}
							],
							gzms: [
						{
							required: true,
							message: '请描述具体情况',
							trigger: ['blur', 'change']
						}
					],
				},
				fileList1: [],
				sblist: [],
				cjlist: ["特容","重容","核电","金工","外场","管束"],
				khlist: ["20T","32T","100T","360T"],
				sb:'',
				sb2:'',
				recordedCount: 0,
				mediaIds: [],
				isRecording: false,
				ddconfig:{
					nonceStr:'SAGEX3',
					timeStamp:0,
				},
				timeOutEvent: 0,
				isClick: false,
			}
		},
		onShow() {
			const YDVNUM = uni.getStorageSync('YDVNUM')
			// console.log(YDVNUM,'query')
			if(this.userInfo.NAME=='杨俊林'){
				// alert(JSON.stringify(YDVNUM))
			}
			if(YDVNUM.YDVNUM){
				this.form.gzsb = '['+YDVNUM.YDVNUM+']'+YDVNUM.YDENAM //|| "[T001]T01"
			console.log(this.form.gzsb,'query')
				uni.setStorageSync('YDVNUM',{})
			}
		},
		onLoad(query) {
			console.log('onLoad')
			const value = uni.getStorageSync('userInfo')
			console.log(value);
			if (value) {
				this.userInfo = value
				this.form.name = this.userInfo.NAME
				this.form.phoneNumber = this.userInfo.PHONE
				console.log(this.userInfo);
			}else{
				console.log('未登录');
			}
			// console.log(query,'query')
			// console.log(this.$route.query,'query')
			
			this.xzsbBtn()
			// this.initdd()
			this.getcce()
		},
		methods: {
			initdd(){
				// alert(location.href)
				this.ddconfig.timeStamp=new Date().getTime()
				uni.request({
				  url: 'http://125.64.76.148:8125/KXJDDDApi/ddconfig?code=1'
				  +'&nonceStr='+this.ddconfig.nonceStr
				  +'&timeStamp='+this.ddconfig.timeStamp
				  +'&url=http://125.64.76.148:8125/repair/', // 替换为实际的接口URL
				  method: 'GET', 
				  data: {},
				  success: (res) => {
					  console.log(res)
					  // uni.$u.toast('initdd.success:'+JSON.stringify(res))
					  // alert('success:'+JSON.stringify(res))
					  dd.config({
					      agentId: '2833818530', // 必填，微应用ID
					      corpId: 'ding81f5b58b1546a0fd35c2f4657eb6378f',//必填，企业ID
					      timeStamp: this.ddconfig.timeStamp, // 必填，生成签名的时间戳
					      nonceStr: this.ddconfig.nonceStr, // 必填，自定义固定字符串。
					      signature: res.data.sign, // 必填，签名
					      type:0/1,   //选填。0表示微应用的jsapi,1表示服务窗的jsapi；不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
					      jsApiList : [
					          'device.audio.startRecord',
					          'device.audio.stopRecord',
					          'device.audio.play',
							  'device.audio.download',
					      ] // 必填，需要使用的jsapi列表，注意：不要带dd。
					  });
					  
					  dd.error(function (err) {
					      uni.$u.toast('钉钉初始化错误，录音功能无法使用: ' + JSON.stringify(err));
					  })//该方法必须带上，用来捕获鉴权出现的异常信息，否则不方便排查出现的问题
				  },
				  fail(err) {
					  alert('fail:'+err)
				  	console.log(err)
				  }
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			extractBracketContent(str) {
				const regex = /【([^】]*)】/g;
				const matches = str.match(regex);
				if (matches) {
					// 如果存在匹配项，我们只关心第一个（如果有多个）
					// 并且去掉两边的中括号
					const firstMatch = matches[0];
					return firstMatch.replace(/【|】/g, '');
				}
						
				return null; // 如果没有找到匹配项，返回 null
			},
			inputccelist(e){
				console.log('inputccelist',e);
				this.form.tbbm1=e;
				const extractedContent = this.extractBracketContent(e);
				this.form.YTBBM=extractedContent;
			},
			async getcce(){
				let GRP1 = {GRP1:[{DIE:'AX2'}]}
				let res = await this.$api.x3.x3request("WSLISTCCE",GRP1)
				let cusbData = JSON.parse(res.message)
				this.ccelist=[];
				for (var i = 0; i < cusbData.GRP1.length; i++) {
					this.ccelist.push('【'+cusbData.GRP1[i].CCE+'】'+cusbData.GRP1[i].DES)
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					if(result==''){
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败',
							url: ''
						}))
						fileListLen++
					}else{
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					}
				}
				console.log(this.fileList1)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://125.64.76.148:8125/KXJDDDApi/file/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								console.log(res)
								resolve(JSON.parse(res.data).data)
							}, 1000)
						},
						fail:(err) => {
							console.log(err)
							resolve('')
						}
					});
				})
			},
			async submit(q) {
				if(q.gzms==undefined || q.gzms==''){
					alert('隐患描述必填')
					return
				}
				if(this.isClick){
					console.log('重复点击')
					return
				}
				for (var i = 0; i < this.fileList1.length; i++) {
					if(this.fileList1[i].url==''){
						uni.$u.toast('存在上传失败的图片，请处理后重新提交')
						return
					}
					if(this.fileList1[i].url.slice(0,4)=='blob'){
						uni.$u.toast('图片上传中，请稍后重试')
						return
					}
				}
				this.isClick = true
				
					// uni.$u.toast('校验通过')
					let GRP1 = {
						GRP1: {
								YFLG: "0",//标识
								ADDRESS: q.adderss,//地点
								PROPOSER: q.name,//申请人
								PROPHONE: q.phoneNumber,//申请人电话
								REPCONT: q.gzms,//报修内容
								YCJ: q.cj,//车间
								YKH: q.kh,//跨号
								YZTH: q.zth,//柱头号
								YTBBM: q.YTBBM,
						}
					}
					GRP1.GRP2=[]
					// alert(this.fileList1)
					for (var i = 0; i < this.fileList1.length; i++) {
						GRP1.GRP2.push({URL:this.fileList1[i].url})
					}
					GRP1.GRP3=[]
					for (var i = 0; i < this.mediaIds.length; i++) {
						GRP1.GRP3.push({MID:this.mediaIds[i]})
					}
					let res = await this.$api.x3.x3request("WSGENXDR2",GRP1)

						if(res.status=="error"){
							alert(res.message);							
							this.isClick = false
							return false;
						}else{
							let resR = JSON.parse(res.message)
							console.log(resR,'resR');
							// console.log(resR.GRP1.WOK,56777);
							if(resR.GRP1.WOK==0){
								// 显示创建成功的消息提示
								uni.showToast({
								   title: '创建成功',
								   icon: 'success',
								   duration: 2000
								});
								this.form.adderss=''
								this.form.gzms=''
								this.form.gzsb=''
								this.fileList1=[]
							}else{
								uni.showToast({
								   title: '创建失败：'+resR.GRP1.WRESULT,
								   icon: 'error',
								   duration: 2000
								});
							}
							this.isClick = false
						}
			},
			xzsbBtn(){
				let GRP1 = {
						GRP1: [{
							YCDIDIAN: this.form.adderss,//地点
							// YUSERID: this.userInfo.ID,//地点
					}]
				}
				let GRP1Json = JSON.stringify(GRP1)
				uni.request({
				  url: 'http://125.64.76.148:8125/KXJDX3Api/x3api', // 替换为实际的接口URL
				  method: 'POST', 
				  data: {
					"username":"APIUSER",
					"passwd":"123",
					"publicName":"WSLISTXDV",
					"method":"run",
					"test":uni.getStorageSync('test') ? "true" : "false",
					"inputXml":JSON.stringify(GRP1)
				  },
				  success: (res) => {
					  let cxsbData = JSON.parse(res.data.message) //将JSON字符串转为对象
					  for (var i = 0; i < cxsbData.GRP1.length; i++) {
					  	this.sblist.push('['+cxsbData.GRP1[i].YDVNUM+']'+cxsbData.GRP1[i].YDENAM)
					  }
					   console.log(cxsbData,'选择设备btn');
					this.sb = this.sb2
					console.log(this.sb)
					// 使用 uni.navigateTo 跳转到 my 页面，并传递数据
					 // uni.navigateTo({url:"/pages/xzsbPages/xzsbPages?cxsbData="+JSON.stringify(cxsbData)})
					
				  },
				  fail: (err) => {
					// 请求失败的处理逻辑
					console.error(err);
				  }
				});
			},
		},
	}
</script>

<style>
	.top{
		height: 80rpx;
		background-color: coral;
	}
	.topText{
		line-height: 80rpx;
		color: white;
		font-size: 28rpx;
		padding-left: 150rpx;
	}
	.two{
		height: 80rpx;
	}
	.btn{
		width: 90%;
		margin: 30rpx auto;
	}
.formBox{
	width: 98%;
	margin:-8rpx 10rpx 10rpx 9rpx ;
}
.labelBox{
	background-color: #f1f1f1;
	display: flex;
	justify-content: space-between;
}
.djlyBox{
	line-height: 80rpx;
}
.djlyBox-text{
	margin-left: -500rpx;
}
.lyIconBox{
	height: 120rpx;
}
.iconBox{
	height: 120rpx;
	width: 120rpx;
	margin: 0 auto;
}
.lyOkBox{
	display: flex;
}
</style>
